import React, { Component, useState } from 'react';
import axios from 'axios';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {
  Button,
  Table,
  Icon,
  Divider,
  Popconfirm,
  Spin,
  Form,
  Modal,
  Input,
  InputNumber,
  Radio,
  Select,
  DatePicker,
  message,
  Upload,
  Cascader,
  Card
} from 'antd';
import { router } from 'umi';
import { getShopId } from '@/utils/localStorage';
import { connect } from 'dva';
import testModal from '@/assets/crmTable.xlsx';
import { baseUrl } from '@/config';
import moment from 'moment';
import {LZFormItem} from "@/components/LZForm";
let AddList = Form.create()(props => {
  const [scope, setScope] = useState('');
  const [productVisible, setproductVisible] = useState(false);
  const [list, setlist] = useState([]);
  const [Modaltotal, settotal] = useState(0);
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [goodslist, setgoodslist] = useState([])
  const [goodslists, setgoodslists] = useState([])
  const [fileList, setfileList] = useState(null)
  const [FromExcel, setFromExcel] = useState([]);
  const [Conditions, setConditions] = useState(null)
  const [InputChan, setInputChan] = useState(null)
  const [currentTotls, setcurrentTotls] = useState(1)
  const FormItem = Form.Item;
  const RadioGroup = Radio.Group;
  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const {
    form: { getFieldDecorator, getFieldValue, validateFields },
    isFormModal,
    loading,
    // productList,
    handleSubmit,
    onCancel,
  } = props;

  let isDisabled = props.location.state && props.location.state.isDisabled || false;
  let current = props.location.state && props.location.state.current || {};
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
      md: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
      md: { span: 17 },
    },
  };

  const validataDate = (rule, value, callback) => {
    if (getFieldValue('type') === '0' && (!value || !value.length)) {
      callback('请选择日期');
    }
    callback();
  };
  const okHandle = e => {
    e.preventDefault();
    validateFields((err, fieldsValue) => {
      if (err) return;
      handleSubmit(fieldsValue);
    });
  };
  const onTheScope = e => {
    setScope(e.target.value)
    if (scope === '') {
      setgoodslist([])
      setgoodslists([])
      setselectedRowKeys([])
    }
  }

  const handleAddProduct = () => {
    props.dispatch({
      type: 'coupons/setBusinessPrdouct',
      payload: {
        pageNumber: 1,
        pageSize: 10,
      },
      callback: (res) => {
        setlist(res.data.records)
        settotal(res.data.total)
      }
    });
    setproductVisible(true)
  };
  const onShowModal = () => {
    setproductVisible(false)
  }

  const onSelectOk = () => {
    let listchul = []
    for (let i = 0; i < goodslist.length; i++) {
      listchul.push({
        value: goodslist[i].productId,
        type: 'PRODUCT',
        description: goodslist[i].name,
      })
    }
    setgoodslists(listchul)
    setproductVisible(false)

  }
  const onSelectChange = (selectedRowKeys, i) => {
    setselectedRowKeys(selectedRowKeys)
    setgoodslist(i)
  };
  const handleChange = (file) => {
    let formdata = new FormData();
    formdata.append('file', file);
    return axios(`${baseUrl}business/coupon/readPhoneFromExcel`, {
      method: 'POST', data: formdata
    }).then((res) => {
      if (res.data.msg === '操作成功') {
        setFromExcel(res.data.data)
        message.success('导入成功')
      } else {
        message.error(res.data.msg)
      }
    })
  }
  const onConditions = e => {
    setConditions(e.target.value)
  }
  const handleSubmits = e => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err) {
        if (getFieldValue('type') === 1) {
          props.dispatch({
            type: 'coupons/couponAdd',
            payload: {
              title: values.title,
              scene: values.scene,
              displayNote: values.displayNote,
              num: values.num,
              minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
              userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
              delayDayNum: values.delayDayNum,
              rangeValues: goodslists,
              phones: FromExcel,
              userRange: values.userRange,
              status: values.status,
              discountAmount: values.discountAmount,
              sourceShopId: getShopId()
            },
          });
        } else {
          props.dispatch({
            type: 'coupons/couponAdd',
            payload: {
              title: values.title,
              scene: values.scene,
              displayNote: values.displayNote,
              num: values.num,
              minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
              userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
              startTime: moment(values.startEnd[0]).format('YYYY-MM-DD hh:mm:ss'),
              endTime: moment(values.startEnd[1]).format('YYYY-MM-DD hh:mm:ss'),
              rangeValues: goodslists,
              phones: FromExcel,
              userRange: values.userRange,
              status: values.status,
              discountAmount: values.discountAmount,
              sourceShopId: getShopId()
            },
          });
        }
      }
    })
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const columns = [
    {
      title: '商品ID',
      dataIndex: 'value',
    },
    {
      title: '商品名称',
      dataIndex: 'description',
    },
  ];
  const Modalcolumns = [
    {
      title: '商品ID',
      dataIndex: 'productId'
    },
    {
      title: '商品名称',
      dataIndex: 'name'
    }
  ]
  const onInputChan = (e) => {
    setInputChan(e.target.value)
  }
  const onSearch = () => {
    props.dispatch({
      type: 'coupons/setBusinessPrdouct',
      payload: {
        pageNumber: 1,
        pageSize: 10,
        productName: InputChan
      },
      callback: (res) => {
        setlist(res.data.records)
        settotal(res.data.total)
      }
    });
  }
  const onIdChang = (e) => {
    setcurrentTotls(e.current)
    props.dispatch({
      type: 'coupons/setBusinessPrdouct',
      payload: {
        pageNumber: e.current,
        pageSize: 10,
        productId: InputChan
      },
      callback: (res) => {
        setlist(res.data.records)
        settotal(res.data.total)
      }
    });
  }
  const onUpload = (info) => {
    if (info.fileList.length === 0) {
      setfileList([])
    } else {
      setfileList([info.fileList[info.fileList.length - 1]])
    }

    // if (info.file.status !== 'uploading') {
    //   console.log(info.file, info.fileList);
    // }
    // if (info.file.status === 'done') {
    //   message.success(`${info.file.name} file uploaded successfully`);
    // } else if (info.file.status === 'error') {
    //   message.error(`${info.file.name} file upload failed.`);
    // }
  }
  // const Remove = (info) => {
  //   setfileList([info])
  // }
  
  const renderScope = () => {
    if (scope === '0') {
      const options = [
        {
          value: 'zhejiang',
          label: 'Zhejiang',
          children: [
            {
              value: 'hangzhou',
              label: 'Hangzhou',
              children: [
                {
                  value: 'xihu',
                  label: 'West Lake',
                },
              ],
            },
          ],
        },
        {
          value: 'jiangsu',
          label: 'Jiangsu',
          children: [
            {
              value: 'nanjing',
              label: 'Nanjing',
              children: [
                {
                  value: 'zhonghuamen',
                  label: 'Zhong Hua Men',
                },
              ],
            },
          ],
        },
      ];
      function onChange(value) {
        console.log(value);
      }
      return (
        <FormItem {...formItemLayout} label="指定类目" required>
          <Cascader
            style={{ width: 200 }}
            options={options}
            expandTrigger="hover"
            onChange={onChange}
          />
          <Select placeholder="请选择分类" style={{ width: 200 }} allowClear>
            <Option value="0">无效</Option>
            <Option value="1">有效</Option>
          </Select>
          <div className="grey-25 ft-12">
            已选中<span className="grey-65">{130}</span>个分类，购买以上分类商品可使用优惠券抵扣金额
          </div>
        </FormItem>
      )
    } else if (scope === '1') {
      return (
        <FormItem {...formItemLayout} label="指定商品" required>
          <Input.Search placeholder="商品名称/货号" style={{ width: 144 }} />
          <Select placeholder="请选择商品" style={{ width: 188 }} allowClear>
            <Option value="0">无效</Option>
            <Option value="1">有效</Option>
          </Select>
          <div className="grey-25 ft-12">
            购买以下分类商品可使用优惠券抵扣金额，已选中<span className="grey-65">{130}</span>分类
          </div>
          <div>
            <div className="scope-selected-goods">
              <div>银色iPhone苹果11 > G123456</div>
              <Icon type="close" />
            </div>
          </div>
          <Button
            onClick={handleAddProduct}
            type="primary"
            shape="round"
            style={{ marginBottom: '30px' }}
          >
            新增商品
          </Button>
          <Table
            rowKey="id"
            bordered
            columns={columns}
            dataSource={goodslists}
            pagination={{
              current: 1,
              pageSize: 10,
            }}
          />
        </FormItem>
      );
    }
    return null;
  }
  return (
    <PageHeaderWrapper title="增加优惠券">
      <Card>
        <Spin spinning={false}>
          <Form onSubmit={handleSubmits}>
            <FormItem {...formItemLayout} label="优惠券类别" required>
              {getFieldDecorator('scene', {
                rules: [{ required: true, message: '请选择优惠券' }],

              })(
                <Select placeholder="请选择">
                  <Option value={'RENT'}>租赁</Option>
                  <Option value={'BUY_OUT'}>买断</Option>
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券名称" required>
              {getFieldDecorator('title', {
                rules: [{ required: true, message: '请输入优惠券名称' }],
                initialValue: current.name,
              })(<Input placeholder="请输入" disabled={isDisabled} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="发放总量" required>
              {getFieldDecorator('num', {
                rules: [{ required: true, message: '请输入发放总量' }],
                initialValue: current.quantity,
              })(<InputNumber placeholder="请输入" style={{ width: '103px' }} />)}
              &nbsp;张
          </FormItem>
            <FormItem {...formItemLayout} label="面额" required>
              {getFieldDecorator('discountAmount', {
                rules: [{ required: true, message: '请输入面额' }],
                initialValue: current.value,
              })(<InputNumber disabled={isDisabled} placeholder="请输入" style={{ width: '103px' }} />)}
              &nbsp;元
          </FormItem>
            <FormItem {...formItemLayout} label="使用条件" required>
              {getFieldDecorator('minAmount', {
                rules: [{ required: true, message: '请输入面额' }],
                initialValue: current.minPurchase || '0'
              })(
                <RadioGroup>
                  <Radio disabled={isDisabled} value="0">不限制</Radio>
                  <Radio disabled={isDisabled} value="1">
                    满&nbsp;
                  {getFieldDecorator('minPurchase', {
                      initialValue: current.minPurchase,
                    })(
                      <InputNumber
                        min={0}
                        precision={2}
                        disabled={getFieldValue('minAmount') === '0' || isDisabled}
                      />
                    )}
                    &nbsp;元
                </Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} required label="每人限领">
              {getFieldDecorator('userLimitNum', {
                initialValue: current.limitNum || 0,
              })(
                <Select>
                  <Option value={0}>无限制</Option>
                  <Option value={1}>1张</Option>
                  <Option value={2}>2张</Option>
                  <Option value={3}>3张</Option>
                  <Option value={4}>4张</Option>
                  <Option value={5}>5张</Option>
                  <Option value={6}>6张</Option>
                  <Option value={7}>7张</Option>
                  <Option value={8}>8张</Option>
                  <Option value={9}>9张</Option>
                  <Option value={10}>10张</Option>
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} required label="时间设置">
              {getFieldDecorator('type', {
                initialValue: current.type || 0,
              })(
                <RadioGroup>
                  <Radio disabled={isDisabled} value={0}>按固定时间</Radio>
                  <Radio disabled={isDisabled} value={1}>按领取日期</Radio>
                </RadioGroup>
              )}
            </FormItem>

            <FormItem {...formItemLayout} colon={false} label=" ">
              {getFieldValue('type') === 0 ? (
                getFieldDecorator('startEnd', {
                  rules: [{ validator: validataDate }],
                  initialValue:
                    current.start && current.end
                      ? [moment(current.start), moment(current.end)]
                      : [null, null],
                })(<RangePicker disabled={isDisabled} />)
              ) : (
                  <div>
                    自领取时{' '}
                    {getFieldDecorator('delayDayNum', {
                      rules: [{ required: true, message: '请输入天数' }],
                      initialValue: current.duration || 0,
                    })(<InputNumber disabled={isDisabled} min={1} precision={0} />)}{' '}
                    天内未使用优惠券自动过期
              </div>
                )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券使用人群" required>
              {getFieldDecorator('userRange', {
                rules: [{ required: true, message: '请选择使用条件' }],
                initialValue: 'ALL'
              })(
                <RadioGroup onChange={onConditions}>
                  <Radio disabled={isDisabled} value="ALL">所有人</Radio>
                  <Radio disabled={isDisabled} value="PART">指定用户</Radio>
                  <Radio disabled={isDisabled} value="NEW">新用户</Radio>
                </RadioGroup>
              )}
            </FormItem>
            {
              Conditions === 'PART' ? <FormItem {...formItemLayout} label="上传" required>
                <Button style={{ width: '104px', height: '31px', marginRight: 30 }}  >
                  <a style={{ textDecoration: 'none' }} href={testModal} download="模版">下载模板</a>
                </Button>
                <Upload
                  fileList={fileList}
                  multiple={true}
                  onChange={onUpload}
                  beforeUpload={(file) => {
                    handleChange(file)
                    return false
                  }}
                >
                  <Button type="primary" ghost>
                    <Icon type="upload" /> 上传
                </Button>
                </Upload>
                {/* <div>
                  手机号：
               {
                    FromExcel.length === 0 ? '- -' :
                      FromExcel.map((item, val) => {
                        return (
                          <span key={val} style={{ marginLeft: 10 }}>{item}</span>
                        )
                      })
                  }
                </div> */}
              </FormItem> : null
            }
            <FormItem {...formItemLayout} label="优惠券适用范围" required >
              <RadioGroup onChange={onTheScope} defaultValue="">
                <Radio disabled={isDisabled} value="">全场通用</Radio>
                <Radio disabled={isDisabled} value="0">指定类目</Radio>
                <Radio disabled={isDisabled} value="1">指定商品</Radio>
              </RadioGroup>
            </FormItem>
            
            {renderScope()}


            <FormItem {...formItemLayout} label="优惠券状态" required>
              {getFieldDecorator('status', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: !current.minPurchase ? 'VALID' : 'INVALID',
              })(
                <RadioGroup >
                  <Radio disabled={isDisabled} value="VALID">有效</Radio>
                  <Radio disabled={isDisabled} value="INVALID">失效</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券展示说明" >
              {getFieldDecorator('displayNote', {
              })(
                <div>
                  <Input.TextArea placeholder='请输入说明' />
                  最多显示12个字
                </div>
              )}
            </FormItem>
            <FormItem wrapperCol={{offset: 5}}>
              <Button type="primary" htmlType="submit">确定</Button>
              <Button onClick={() => router.go(-1)}
                      style={{marginRight: 20 }}>取消</Button>
            </FormItem>
          </Form>
        </Spin>
        <Modal
          visible={productVisible}
          title="选择商品"
          width={750}
          onOk={onSelectOk}
          onCancel={onShowModal}
        >
          <Spin spinning={loading}>
            <div style={{ marginBottom: 20 }}>
              <Input
                style={{ width: '50%' }}
                placeholder="输入商品名称进行搜索"
                onChange={onInputChan}
              />
              <Button
                style={{ marginLeft: 20 }}
                type="primary"
                icon="search"
                onClick={onSearch}
              >
                搜索
            </Button>
            </div>
            <Table
              rowKey="productId"
              dataSource={list}
              columns={Modalcolumns}
              pagination={{
                current: currentTotls,
                pageSize: 10,
                total: Modaltotal
              }}
              onChange={onIdChang}
              rowSelection={rowSelection}
            />
          </Spin>
        </Modal>
      </Card>
    </PageHeaderWrapper>
  );
});
export default connect(({ coupons, loading }) => ({ ...coupons, loading: loading.models.coupons, }))(AddList)

